<?php
namespace app\admin\model;

use think\Model;
use app\admin\controller\Attachment;
use think\Db;
class ArticleModel extends Model
{
    // 确定链接表名
    protected $name = 'articles';

    /**
     * 查询文章
     * @param $where
     * @param $offset
     * @param $limit
     */
    public function getArticlesByWhere($where, $offset, $limit)
    {
        return $this->where(function($query)use($where){
			foreach($where as $k => $v){
				$query->whereOr($k,$v[0],$v[1]);
			}
		})->limit($offset, $limit)->order('id desc')->select();
    }

    /**
     * 根据搜索条件获取所有的文章数量
     * @param $where
     */
    public function getAllArticles($where)
    {
        return $this->where($where)->count();
    }

    /**
     * 添加文章
     * @param $param
     */
    public function addArticle($param)
    {
        try{
            $result = $this->validate('ArticleValidate')->save($param);
            if(false === $result){
                // 验证失败 输出错误信息
                return msg(-1, '', $this->getError());
            }else{

                return msg(1, url('articles/index'), '添加文章成功');
            }
        }catch (\Exception $e){
            return msg(-2, '', $e->getMessage());
        }
    }

    /**
     * 编辑文章信息
     * @param $param
     */
    public function editArticle($param){
        try{
			$before = $this->where('id',$param['id'])->find();
			// 封面图片不留垃圾
			if($param['thumbnail'] != $before['thumbnail']){
				$attach_id = DB::name('attachment')->where('url',$before['thumbnail'])->value('id');
				$attach_ctrl = new Attachment();
				$attach_ctrl->delAttach(array($attach_id));
			}
            $result = $this->validate('ArticleValidate')->save($param, ['id' => $param['id']]);
            if(false === $result){
                // 验证失败 输出错误信息
                return msg(-1, '', $this->getError());
            }else{
                return msg(1, url('articles/index'), '编辑文章成功');
            }
        }catch(\Exception $e){
            return msg(-2, '', $e->getMessage());
        }
    }

    /**
     * 根据文章的id 获取文章的信息
     * @param $id
     */
    public function getOneArticle($id)
    {
        return $this->where('id', $id)->find();
    }

    /**
     * 删除文章
     * @param $id
     */
    public function delArticle($id)
    {
        try{
			// 封面图片不留垃圾
			$thumb = $this->where('id', $id)->value('thumbnail');
			$attach_id = DB::name('attachment')->where('url',$thumb)->value('id');
			$attach_ctrl = new Attachment();
			$attach_ctrl->delAttach(array($attach_id));
            $this->where('id', $id)->delete();
            return msg(1, '', '删除文章成功');
        }catch(\Exception $e){
            return msg(-1, '', $e->getMessage());
        }
    }
}
